/*
    * @module:views/budget/investBudget/budgetRelease
    * @author:zengfx
    * @date:2020-12-17
    * 预算下达
*/
<template>
  <div class="budgetRelease_container">
    <div>
      <el-form :inline="true" :model="form" label-width="60px">
        <el-form-item label="区域">
          <dx-cascader :area_id.sync="form.areaId" :maxLevel="2" />
          <!-- <span v-if="lvl == 3">{{ areaName }}</span> -->
        </el-form-item>
        <el-form-item label="年度">
          <el-date-picker v-model="form.acctYear" type="year" size="mini" placeholder="选择年" value-format="yyyy"></el-date-picker>
        </el-form-item>
        <el-form-item label="投资专项" label-width="80">
          <el-select v-model="form.specialId" size="mini" clearable>
            <el-option v-for="(it, i) in idList" :key="i" :label="it.specialName" :value="it.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="handle_search()">查询</el-button>
          <el-button size="mini" type="orange" @click="handle_export()">导出</el-button>
        </el-form-item>
        <el-form-item class="fr" v-if="lvl == 2">
          <el-button size="mini" @click="template_download()">模板下载</el-button>
          <el-button size="mini" type="warning" @click="
                            dialogVisible = true;
                            importForm.specialName = '';
                            importForm.specialId = '';
                            importForm.year = '';
                            importForm.description = '';
                            fileList = [];
                        ">导入</el-button>
        </el-form-item>
      </el-form>
      <div class="tableBox">
        <!-- @expand-change="exChange" -->
        <el-table height="73vh" ref="table" size="mini" :header-cell-style="{ background: '#eef1f6' }" :data="tableData" v-loading="tableLoading" style="width: 100%" border>
          <el-table-column type="expand" width="1">
            <template slot-scope="scope">
              <el-table ref="tableChild" :data="scope.row.childData" align="center" border>
                <el-table-column prop="indexName" label="专业项"></el-table-column>
                <el-table-column :label="item.label" :prop="'value' + item.id" v-for="(item, index) in titleList" :key="index"></el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="预算年度" prop="testYear" width="100"></el-table-column>
          <el-table-column label="下达版本" width="100" prop="version"></el-table-column>

          <el-table-column label="投资专项" width="100" prop="specialName"></el-table-column>
          <el-table-column label="下达说明" show-overflow-tooltip prop="rexplain"></el-table-column>
          <el-table-column label="状态" width="100" prop="statusText"></el-table-column>
          <el-table-column min-width="100" :label="item.label" :prop="'value' + item.id" v-for="(item, index) in titleList" :key="index"></el-table-column>
          <el-table-column label="操作" width="210">
            <template slot-scope="scope">
              <el-button type="text" @click="handle_detail(scope.row)">明细</el-button>
              <el-button type="text" :disabled="lvl != 3" @click="handle_change(scope.row)">调整</el-button>
              <el-button type="text" :disabled="
                                    scope.row.id == '001' ||
                                    lvl == 3 ||
                                    scope.row.status == '1'
                                " @click="handle_down(scope.row)">下达</el-button>
              <el-button type="text" :disabled="scope.row.id == '001' || lvl == 3" @click="handle_del(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog title="导入文件" append-to-body :visible.sync="dialogVisible" width="450px">
      <el-form :model="importForm" ref="importForm" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年度" prop="year">
              <el-date-picker style="width: 150px" v-model="importForm.year" type="year" size="mini" placeholder="选择年" value-format="yyyy"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投资专项" label-width="80" prop="specialId">
              <el-select v-model="importForm.specialId" size="mini" style="width: 125px">
                <el-option v-for="(it, i) in idList2" :key="i" :label="it.specialName" :value="it.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="下达说明" :label-width="formLabelWidth">
          <el-input v-model="importForm.description" autocomplete="off" placeholder="请输入下达说明"></el-input>
        </el-form-item>
        <el-form-item label="上传文件" :label-width="formLabelWidth">
          <el-upload :limit="1" accept=".xls, .xlsx" class="avatar-uploader" :auto-upload="false" :file-list="fileList" :on-change="changeFile" action>
            <el-button size="mini" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <div class="dialog-footer">
          <el-button size="mini" type="primary" @click="handle_import(1)">确定下达</el-button>
          <el-button size="mini" type="primary" @click="handle_import(0)">确定保存</el-button>
          <el-button size="mini" @click="dialogVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { $budgetAPI } from "@/api/";
import { getSessionStorage } from "@/common/js/storage";
import prefixAPI from "@/api/prefixAPI";
import { getCookie } from "@/common/js/cookie";
export default {
  data() {
    return {
      form: {
        areaId: "",
        acctYear: this.moment().format("YYYY"),
        specialId: "",
      },
      importForm: {
        description: "",
        file: null,
        year: this.moment().format("YYYY"),
        specialId: "",
      },
      yearList: [],
      tableData: [],
      accountInfo: null,
      tableLoading: false,
      exportLoading:false,
      titleList: [],
      dialogVisible: false,
      formLabelWidth: "80px",
      fileList: [],
      rules: {
        year: [
          { required: true, message: "请选择年份", trigger: "blur" },
        ],
        specialId: [
          {
            required: true,
            message: "请选择投资专项",
            trigger: "blur",
          },
        ],
        // description: [
        //     {
        //         required: true,
        //         message: "请输入下达说明",
        //         trigger: "blur",
        //     },
        // ],
      },
      param: "",
      lvl: "",
      idList: [],
      idList2: [],
      areaName: "",
      activeName: "first",
    };
  },
  mounted() { },
  watch: {
    "form.acctYear"(newValue, oldValue) {
      var that = this;
      console.log(newValue, oldValue)
      $budgetAPI.getIDList(
        {
          acctYear: that.form.acctYear,
        },
        (res) => {
          that.idList2 = res.content
          that.idList = [{
            id: "",
            specialName: "全部",
          }, ...res.content];
        }
      );
    }
  },
  methods: {
    init() {
      var that = this;

      that.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
      that.form.areaId = that.accountInfo.areaId;
      that.lvl = that.accountInfo.areaLvl;
      that.getInitData();
    },
    // 批量导入上传文件传递数据
    changeFile(file, fileList) {
      this.fileList = fileList;
      this.param = new FormData();
      this.param.append("file", file.raw);
    },
    handle_search() {
      this.getReleaseDataList();
    },
    // 导入
    handle_import(type) {
      var that = this;
      this.$refs["importForm"].validate((valid) => {
        if (valid) {
          if (this.fileList.length == 0) {
            this.$message({
              message: "请选择需要上传的文件",
              type: "warning",
            });
            return false;
          }
          this.param.append(
            "description",
            this.importForm.description
          );
          this.param.append("token", getCookie("token"));
          this.param.append("areaId", this.form.areaId);
          that.param.append("acctYear", this.importForm.year);
          that.param.append("isRelease", type);
          that.param.append("specialId", this.importForm.specialId);
          that.idList.map((it) => {
            if (it.id == that.importForm.specialId) {
              that.param.append("specialName", it.specialName);
            }
          });

          $budgetAPI.importReleaseData(
            that.param,
            (res) => {
              if (res.code == 0) {
                this.$message({
                  message: "导入成功",
                  type: "success",
                });
                this.getReleaseDataList();
              } else {
                this.$message.error(res.message);
              }
              this.dialogVisible = false;
            },
            (err) => {
              console.log(err);
              this.dialogVisible = false;
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除
    handle_delete(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $budgetAPI.deleteReleaseData(
            { id: id },
            (res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getReleaseDataList();
              } else {
                this.$message.error(res.message);
              }
            },
            (err) => {
              console.log(err);
            }
          );
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 获取年份
    getReleaseMonths() {
      return new Promise((resolve) => {
        $budgetAPI.getReleaseMonths(
          {
            areaId: this.form.areaId,
          },
          (res) => {
            if (res.code == 0) {
              resolve(res.content);
            }
          },
          (err) => {
            console.log(err);
          }
        );
      });
    },
    // 获取列表
    getReleaseDataList() {
      var that = this,
        status = [
          "未下达 ",
          "已下达",
          "审核通过",
          "审核未通过",
          "已作废",
        ];
      that.tableLoading = true;
      $budgetAPI.getReleaseDataList(
        this.form,
        (res) => {
          if (res.code == 0) {
            // res.areaId res.areaName 市级别 返回内容 省级别返回为空
            if (that.lvl == 3) {
              that.form.areaId = res.areaId;
              that.areaName = "杭州" || res.areaName;
            }
            res.content.data.map((it) => {
              it["childData"] = [];
              it.detailList.map((item, i) => {
                it["value" + item.areaId] = item.indexVal;
              });
              it.statusText = status[it.status];
            });
            this.tableData = res.content.data;
            const zip = ([x, ...xs], [y, ...ys]) => {
              if (x === undefined || y === undefined) {
                return [];
              } else {
                return [[x, y], ...zip(xs, ys)];
              }
            };
            this.titleList = zip(
              res.content.areaNames,
              res.content.areaIds
            ).map(([label, id]) => ({ label, id }));
          }
          this.tableLoading = false;
        },
        (err) => {
          this.tableLoading = false;
        }
      );
    },
    //预算下达导出
    handle_export() {
      
      let token = getCookie("token");
      let areaId = "";
      if (this.form.areaId) {
        areaId = this.form.areaId;
      } else {
        areaId = this.accountInfo.areaId;
      }
      let specialId = this.form.specialId ? "" : this.form.specialId;
      let acctYear = this.form.acctYear ? this.form.acctYear : this.moment().format("YYYY");
      console.log(acctYear);
      if (process.env.NODE_ENV == "development") {
        window.location.href = prefixAPI.loc +
          "/api/incomeBudget/exportReleaseData?areaId=" + areaId +
          "&acctYear=" + acctYear + "&specialId=" + specialId +"&token="+token;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href = prefixAPI.hp +
          "/api/incomeBudget/exportReleaseData?areaId=" + areaId +
          "&acctYear=" + acctYear + "&specialId=" + specialId +"&token="+token;
      }
      
    },
    // 模板下载
    template_download() {
      let token = getCookie("token");
      let areaId = this.form.areaId;
      let acctYear = this.form.acctYear ? this.form.acctYear : "";
      // 根据不同模式切换不同的路径
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          "/api/incomeBudget/releaseTemplateDownLoad?areaId=" +
          areaId +
          "&acctYear=" +
          acctYear +
          "&token=" +
          token;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          "/api/incomeBudget/releaseTemplateDownLoad?areaId=" +
          areaId +
          "&acctYear=" +
          acctYear +
          "&token=" +
          token;
      }
      $budgetAPI.releaseTemplateDownLoad(this.form, (res) => {
        if (res.code == 0) {
        }
      });
    },
    // 初始化
    async getInitData() {
      let that = this,
        list;
      // that.yearList = await that.getReleaseMonths();
      list = await that.getIdList();

      that.idList2 = list;
      that.idList = [{
        id: "",
        specialName: "全部",
      }, ...list];
      that.getReleaseDataList();
    },
    getIdList() {
      var that = this;

      return new Promise((resolve) => {
        $budgetAPI.getIDList(
          {
            acctYear: that.form.acctYear,
          },
          (res) => {
            resolve(res.content);
          }
        );
      });
    },
    handle_detail(row) {
      var that = this,
        $table = that.$refs.table,
        token = getCookie("token");

      $table.toggleRowExpansion(row);
      $budgetAPI.getSpecialDetail(
        {
          releaseId: row.id,
          token: token,
          acctYear: that.form.year,
          specialId: that.form.specialId,
        },
        (res) => {
          res.content.data.map((it) => {
            it.detailList.map((item, i) => {
              it["value" + item.areaId] = item.indexValue;
            });
          });
          that.tableData.map((it) => {
            if (it.id == row.id) {
              it.childData = res.content.data;
            }
          });
        }
      );
    },
    exChange(row, rowList) {
      console.log(row, 1, rowList);
    },
    handle_down(row) {
      this.$confirm("是否下达?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $budgetAPI.getDown(
          {
            releaseId: row.id,
          },
          (res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "下达成功!",
              });
              this.getReleaseDataList();
            }
          }
        );
      });
    },
    handle_change(row) {
      var that = this;

      that.$router.push({
        path: "/budget/modulation",
        query: { id: row.id, type: "change" },
      });
    },
    handle_del(row) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $budgetAPI.getDeleteDown(
          {
            releaseId: row.id,
          },
          (res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getReleaseDataList();
            }
          }
        );
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>